import { createRouter, createWebHistory } from 'vue-router';
import Chat from '../views/Chat.vue';
import UserManagement from '../views/UserManagement.vue';
import Login from '../views/Login.vue';
import KnowledgeBase from '../views/KnowledgeBase.vue';
import InventoryManagement from '../views/InventoryManagement.vue';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    },
    {
      path: '/chat',
      name: 'chat',
      component: Chat
    },
    {
      path: '/users',
      name: 'users',
      component: UserManagement
    },
    {
      path: '/knowledge',
      name: 'knowledge',
      component: KnowledgeBase
    },
    {
      path: '/inventory',
      name: 'inventory',
      component: InventoryManagement
    }
  ]
});

// 添加路由守卫验证token和权限
router.beforeEach((to, _from, next) => {
  const getCookie = (name: string) => {
    const cookieStr = document.cookie;
    const cookies = cookieStr.split('; ');
    for (const cookie of cookies) {
      const [key, value] = cookie.split('=');
      if (key === name) {
        return decodeURIComponent(value);
      }
    }
    return null;
  };
  const cookieToken = getCookie('token');
  
  // 目标路由不是登录页且没有token时，重定向到登录页
  if (to.name !== 'login' && !cookieToken) {
    next({ name: 'login' });
    return;
  } 
  
  // 已登录用户访问登录页时，重定向到chat页
  if (to.name === 'login' && cookieToken) {
    next({ name: 'chat' });
    return;
  }
  
  // 检查用户是否有chat权限，如果没有则跳转到其他有权限的页面
  if (to.name === 'chat' && cookieToken) {
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      const { permissions } = JSON.parse(userInfo);
      const hasPermission = (perm: string) => permissions && (permissions.includes('*') || permissions.includes(perm));
      
      if (!hasPermission('chat')) {
        // 检查用户是否有其他权限
        if (hasPermission('user')) {
          next({ name: 'users' });
          return;
        } else {
          // 检查实验室权限：researchRoleInfos不为空或roleName为"高级实验室管理员"
          const { researchRoleInfos } = JSON.parse(userInfo);
          if (researchRoleInfos && Object.keys(researchRoleInfos).length > 0) {
            next({ name: 'inventory' });
            return;
          }
        } 
        
        // 检查知识库权限：knowledgeBaseGroupRoleInfos不为空或roleName为"高级资料库管理员"
        const { knowledgeBaseGroupRoleInfos } = JSON.parse(userInfo);
        if (knowledgeBaseGroupRoleInfos && Object.keys(knowledgeBaseGroupRoleInfos).length > 0) {
          next({ name: 'knowledge' });
          return;
        } else {
          // 所有权限都没有，退出登录
          localStorage.clear();
          document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
          next({ name: 'login' });
          return;
        }
      }
    }
  }

  // 权限检查：根据permissions数组判断是否有权限访问特定页面
  if (to.name === 'users') {
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      const { permissions } = JSON.parse(userInfo);
      
      // 检查权限：如果有*则拥有所有权限
      if (permissions && permissions.includes('*')) {
        next();
        return;
      }
      
      // 路由名称与所需权限的映射
      const routePermissionMap: Record<string, string[]> = {
        'chat':['chat'],
        'users': ['user']
      };
      
      // 获取当前路由所需的权限列表
      const requiredPermissions = routePermissionMap[to.name.toString()];
      
      // 检查是否有所需的权限
      if (!permissions || !requiredPermissions.every(permission => permissions.includes(permission))) {
        // 没有所需的权限，清除登录信息并重定向到登录页面
        localStorage.clear();
        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        next({ name: 'login' });
        return;
      }
    }
  } else if (to.name === 'inventory') {
    // 库存管理页面的特殊权限检查
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      const { researchRoleInfos, permissions } = JSON.parse(userInfo);
      
      // 检查权限：如果有*则拥有所有权限
      if (permissions && permissions.includes('*')) {
        next();
        return;
      }
      
      // 检查库存权限：researchRoleInfos不为空或roleName为"高级实验室管理员"
      if (researchRoleInfos && Object.keys(researchRoleInfos).length > 0) {
        next();
        return;
      } else if (permissions && permissions.includes('inventory')) {
        // 保留原有的权限检查逻辑
        next();
        return;
      } else {
        // 没有库存权限，清除登录信息并重定向到登录页面
        localStorage.clear();
        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        next({ name: 'login' });
        return;
      }
    }
  } else if (to.name === 'knowledge') {
    // 知识库页面的特殊权限检查
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      const { knowledgeBaseGroupRoleInfos, permissions } = JSON.parse(userInfo);
      
      // 检查权限：如果有*则拥有所有权限
      if (permissions && permissions.includes('*')) {
        next();
        return;
      }
      
      // 检查知识库权限：knowledgeBaseGroupRoleInfos不为空或roleName为"高级资料库管理员"
      if (knowledgeBaseGroupRoleInfos && Object.keys(knowledgeBaseGroupRoleInfos).length > 0) {
        next();
        return;
      } else {
        // 没有知识库权限，清除登录信息并重定向到登录页面
        localStorage.clear();
        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        next({ name: 'login' });
        return;
      }
    }
  }
  
  // 其他情况正常跳转
  next();
});

// 创建一个简单的事件总线
export const eventBus = {
  listeners: new Map<string, Array<() => void>>(),
  on(event: string, callback: () => void) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event)?.push(callback);
  },
  emit(event: string) {
    this.listeners.get(event)?.forEach(callback => callback());
  }
};

// 添加全局的afterEach钩子
router.afterEach((to, from) => {
  // 只有当不是从登录页面跳转到chat页面时，才触发获取消息通知
  // 因为登录页面已经触发了一次
  if (to.path === '/chat' && from.path !== '/') {
    eventBus.emit('fetch-notifications');
  }
});

export default router;